package org.example.exception;

import org.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// 全局异常处理
@RestControllerAdvice
public class GlobalExceptionHanler {



    @ExceptionHandler(Exception.class)
    public Result handlerException(Exception e) {

        e.printStackTrace(); // 将异常信息打印到控制台
        String err = e.getMessage() ;
        String regex  = "jakarta.validation";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(e.toString());
        System.out.println("简化报错： "+ err);

        if (StringUtils.hasLength(err) && matcher.find()) {

            String[] arr1 = err.split(", ");
            String[] errArr = new String[2];
            for (int i = 0; i < arr1.length; i++) {
                String[] arr = arr1[i].split("\\.|: ");
                errArr[i] = (i == 0 ? "" : "、") + arr[1] ;
            }

            err =  Arrays.toString(errArr) + "参数数据类型不正确或不能为空";

        } else if (err.indexOf("[Field error in object") != -1) {
            err= "有参数为空或没有传";
        } else {
            err= "操作失败";
        }
        return new Result().error(err);


    }
}
